#include "logAndCreat.hpp"

const int flag = IPC_CREAT | IPC_EXCL; //创建全新的共享内存
int main()
{
   

    key_t key = CreateKey();
    log() << "key:" << key << endl;

    //创建共享内存
    log() << "begin to create shm" << endl;
    int shmid = shmget(key, MEM_SIZE, flag | 0666);
    if (shmid < 0)
    {
        log() << "shmget:" << strerror(errno) << endl;
        return 2;
    }
    cout << "create shm success,shmid:" << shmid << endl;

    //将共享内存和自己的进程产生关联attach
    char *str = (char *)shmat(shmid, nullptr, 0);
    log() << "attach shm:" << shmid << endl;

    //创建命名管道写在key前面会阻塞,因为第二个参数默认阻塞
    CreateFifo();
    int fd = open(FIFO_FILE, O_RDONLY); //打开命名管道
    assert(fd >= 0);

    while (1)
    {
        uint32_t values = 0;
        //从命名管道读取（阻塞）,client写入共享内存后会往命名管道写入信息
        ssize_t s = read(fd, &values, sizeof(values));
        if (s <= 0)
            break;
        printf("%s\n", str);
        sleep(1);
    }

    //共享内存去关联
    shmdt(str);
    log()<<"detach shm:"<<shmid<<" success!"<<endl;

    //删除共享内存
    shmctl(shmid,IPC_RMID,nullptr);
    log()<<"delete shm:"<<shmid<<" success!"<<endl;

    //关闭并删除文件
    close(fd);
    unlink(FIFO_FILE);
    
    return 0;
}
